package com.czy.utilslib.photo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.core.content.FileProvider;

import com.czy.utilslib.R;
import com.czy.utilslib.debug.DebugUtil;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *  拍照工具：
 *      1.拍照之后图片通过uri读取到imageview
 *      2.拍照之后图片保存到相册文件夹下
 *      3.拍照之后，图片通过ImageUtils转化为Bitmap缓存在内存（压缩上传到Spring Boot）
 */
public class TakePhotoUtil {
    private static String TAG = TakePhotoUtil.class.getSimpleName();

    public static final int REQUEST_PHOTO_CODE = 985;
    private File mImageFile;
    private Uri mImageUri;

    public File getmImageFile() {
        return mImageFile;
    }
    public Uri getmImageUri(){
        return mImageUri;
    }

    @SuppressLint("QueryPermissionsNeeded")
    public void takePhoto(Activity activity, int code){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //这句作用是如果没有相机则该应用不会闪退，要是不加这句则当系统没有相机应用的时候该应用会闪退
        if (intent.resolveActivity(activity.getPackageManager()) != null){
            //创建用来保存照片的文件
            mImageFile = createImageFile(activity);
            if(mImageFile != null){
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    //7.0以上要通过FileProvider将File转化为Uri
                    String authority = activity.getApplicationInfo().packageName + ".fileprovider";
                    // FileProvider需要在Manifest种申明
                    mImageUri = FileProvider.getUriForFile(activity, authority, mImageFile);
                    DebugUtil.logV("Runtime","mImageUri:" + mImageUri);
                }
                else {
                    //7.0以下则直接使用Uri的fromFile方法将File转化为Uri
                    mImageUri = Uri.fromFile(mImageFile);
                }
                //将用于输出的文件Uri传递给相机
                intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
                if (code == REQUEST_PHOTO_CODE) {
                    intent.putExtra("android.intent.extras.CAMERA_FACING", Camera.CameraInfo.CAMERA_FACING_FRONT);
                    intent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true);
                }
                //打开相机
                activity.startActivityForResult(intent, code);
            }
        }
    }

    public void takePhotoV2(Activity activity, boolean isFrontCamera, ActivityResultLauncher<Intent> launcher){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        // 确保设备上有可用的相机
        if (intent.resolveActivity(activity.getPackageManager()) != null) {
            // 创建用来保存照片的文件
            mImageFile = createImageFile(activity);
            if (mImageFile != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    // 7.0及以上版本通过FileProvider获取Uri
                    String authority = activity.getApplicationInfo().packageName + ".fileprovider";
                    mImageUri = FileProvider.getUriForFile(activity, authority, mImageFile);
                    DebugUtil.logI(TAG, "mImageUri：" + mImageFile);
                } else {
                    // 7.0以下直接使用Uri的fromFile方法
                    mImageUri = Uri.fromFile(mImageFile);
                }
                // 将用于输出的文件Uri传递给相机
                intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
                // 根据boolean值设置摄像头
                if (isFrontCamera) {
                    intent.putExtra("android.intent.extras.CAMERA_FACING", Camera.CameraInfo.CAMERA_FACING_FRONT);
                    intent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true);
                } else {
                    intent.putExtra("android.intent.extras.CAMERA_FACING", Camera.CameraInfo.CAMERA_FACING_BACK);
                    intent.putExtra("android.intent.extra.USE_FRONT_CAMERA", false);
                }
                // 使用ActivityResultLauncher启动相机
                launcher.launch(intent);
            }
            else {
                DebugUtil.logE(TAG, "保存数据的文件为空");
            }
        }
    }

    /**
     * 创建用来存储图片的文件，以时间来命名就不会产生命名冲突
     *
     * @return 创建的图片文件
     */
    @SuppressLint("SimpleDateFormat")
    private File createImageFile(Activity activity) {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File imageFile = null;
        try {
            imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageFile;
    }

    public void handleResult(int requestCode, int resultCode, Intent data){
        if(resultCode == Activity.RESULT_OK){
            if (requestCode == REQUEST_PHOTO_CODE){
                Uri imageUri = mImageUri;
            }
        }
    }

    public Uri handleResultAndLoad(int requestCode, int resultCode, Intent data, Activity activity, ImageView imageView){
        if(resultCode == Activity.RESULT_OK){
            if (requestCode == REQUEST_PHOTO_CODE){
                Uri imageUri = mImageUri;
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), getmImageUri());
                    imageView.setImageBitmap(bitmap);
                    return getmImageUri();
                } catch (IOException e) {
                    imageView.setImageResource(R.drawable.icon_default_acatar);
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
